/*************************************************************************
	> File Name: signalfd.c
	> Author: Angel Criss
	> Blog: blog.abbycin.tk 
	> Created Time: Wed 25 Jun 2014 08:01:31 PM CST
 ************************************************************************/

// man 2 read
#include<stdio.h>
#include<sys/signalfd.h>
#include<signal.h>
#include<unistd.h>
#include<errno.h>

int main(int argc,char *argv[])
{
    sigset_t block;  //declare mask
    struct signalfd_siginfo sigfd;
    int sig;
    int fd,i=0;
    ssize_t fdread;

    if(argc<2)
    {
        printf("%s argv1(must be a number)\n",argv[0]);
        _exit(errno);
    }
    printf("%s's PID: %ld\n",argv[0],(long)getpid());

    sigemptyset(&block);

    if(sigaddset(&block,atoi(argv[1]))==-1) //将第二个参数作为大小加入信号集,也可以用一个循环把多个信号加入信号集
    {
            perror("sigaddset:");
            _exit(errno);
    }
    if(sigprocmask(SIG_BLOCK,&block,NULL)==-1) // block the signal added in the "block"
    {
        perror("sigprocmask:");
        _exit(errno);
    }
    fd=signalfd(-1,&block,0); //not use flag=SFD_CLOEXEC or SFD_NONBLOCK
    if(fd==-1)
    {
        perror("signalfd:");
        _exit(errno);
    }
    for(;;)
    {
        fdread=read(fd,&sigfd,sizeof(struct signalfd_siginfo)); /*
                                                                   read once and blocked and wait for a signal to continue read
                                                                   */
        if(fdread!=sizeof(struct signalfd_siginfo))
        {
            perror("read");
            _exit(errno);
        }
        printf("cought sig for \e[43m %d \e[0m\n",i);
        i+=1;
        printf("ssi_signo:%d ssi_code: %d ssi_pid:%d \n",sigfd.ssi_signo,sigfd.ssi_code,sigfd.ssi_pid);
    }
}
